import {createRouter, createWebHistory} from 'vue-router'
import { useMainStore } from '../store';

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'Layout',
            redirect: '/home',
            component: () => import('../layout/Layout.vue'),
            children: [
                {
                    path: '/home',
                    name: 'Home',
                    component: () => import('../views/HomeAdmin.vue'),
                },
                {
                    path: '/book',
                    name: 'Book',
                    component: () => import('../views/BookAdmin.vue'),
                },
                {
                    path: '/barrow',
                    name: 'Barrow',
                    component: () => import('../views/BarrowAdmin.vue'),
                },
                {
                    path: '/return',
                    name: 'Return',
                    component: () => import('../views/ReturnAdmin.vue'),
                },
                {
                    path: '/person',
                    name: 'Person',
                    component: () => import('../views/PersonAdmin.vue'),
                }
            ]
        },
        // {
        //     path: '/login',
        //     name: 'Login',
        //     component: () => import('../views/Login.vue'),
        // },
        {
            path: '/login',
            name: 'Login',
            component: () => import('../views/LoginAdmin.vue'),
        },
        {
            path: '/register',
            name: 'Register',
            component: () => import('../views/Register.vue'),
        },
        {
            path: '/',
            redirect: '/home'
        },
        {
            path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component: () => import('../views/LoginAdmin.vue'),
        }
    ],
});


// 路由守卫
router.beforeEach((to, from) => {
    const store = useMainStore();
    const isLogin = store.isLogin;
    if (to.path === '/login' || to.path === '/register') {
        if (isLogin) {
            return '/home';
        }
    } else {
        if (!isLogin) {
            return '/login';
        }
    }
});

export default router